import os
from pptflow.config.setting import Setting


def get_default_setting(os_name: str = 'Windows', language: str = 'en', tts_service_provider: str = 'kokoro'):
    setting = Setting()
    setting.language = language
    get_default_subtitle_path(setting, os_name, language)
    get_default_subtitle_length(setting)
    get_default_tts_settings(setting, tts_service_provider=tts_service_provider)

    return setting


def get_default_subtitle_path(setting: Setting, os_name: str = 'Windows', language: str = 'en'):
    if os_name == "Windows":
        if language == 'zh':
            setting.subtitle_font_name = 'STSong'
            setting.subtitle_font_path = 'C:/Windows/Fonts/STSONG.TTF'
        elif language == 'en':
            setting.subtitle_font_name = 'Microsoft YaHei'
            setting.subtitle_font_path = 'C:/Windows/Fonts/msyh.ttc'
    elif os_name == "Linux":
        if language == 'zh':
            setting.subtitle_font_name = 'WenQuanYi Zen Hei'
            setting.subtitle_font_path = '/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc'
        elif language == 'en':
            setting.subtitle_font_name = 'DejaVu Sans'
            setting.subtitle_font_path = '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf'
    elif os_name == "Darwin":
        if language == 'zh':
            setting.subtitle_font_name = 'Songti SC'
            setting.subtitle_font_path = '/System/Library/Fonts/Supplemental/Songti.ttc'
        elif language == 'en':
            setting.subtitle_font_name = 'Arial'
            setting.subtitle_font_path = '/System/Library/Fonts/Supplemental/Arial.ttf'
    else:
        raise NotImplementedError(f"Unsupported OS: {os_name}")


def get_default_subtitle_length(setting: Setting):
    if setting.language == 'en':
        setting.subtitle_length = 12
    elif setting.language == 'zh':
        setting.subtitle_length = 18
    else:
        pass


def get_default_tts_settings(setting: Setting, tts_service_provider: str = 'kokoro'):
    """
    Initialize TTS settings based on the specified provider.
    
    Args:
        setting: The Setting object to update
        tts_service_provider: The name of the TTS provider to use
    """
    # Import logger here to avoid circular imports
    from pptflow.utils import mylogger
    logger = mylogger.get_logger(__name__)
    
    # Normalize the provider name (handle different formats like fish_speech, fish-speech, fishspeech)
    provider = tts_service_provider.lower().replace('-', '_')
    logger.info(f"Initializing TTS settings for provider: {provider}")
    
    try:
        if provider == 'kokoro':
            setting.tts_service_provider = 'kokoro'
            logger.info("Initialized Kokoro TTS settings")
            
        elif provider == 'azure':
            setting.tts_service_provider = 'azure'
            setting.tts_speech_region = os.getenv("TTS_AZURE_SPEECH_REGION", 'eastasia')
            setting.tts_api_key = os.getenv("TTS_AZURE_SPEECH_KEY")
            logger.info("Initialized Azure TTS settings")
            
        elif provider == 'baidu':
            setting.tts_service_provider = 'baidu'
            setting.baidu_app_id = os.getenv("BAIDU_APP_ID")
            setting.baidu_api_key = os.getenv("BAIDU_API_KEY")
            setting.baidu_secret_key = os.getenv("BAIDU_SECRET_KEY")
            logger.info("Initialized Baidu TTS settings")
            
        elif provider in ['fish_speech', 'fishspeech']:
            setting.tts_service_provider = 'fish_speech'
            setting.fish_speech_api = os.getenv("FISH_SPEECH_API", "http://localhost:8330")
            setting.fish_speech_model = os.getenv("FISH_SPEECH_MODEL", "fish-speech-1.1")
            setting.fish_speech_speaker = os.getenv("FISH_SPEECH_SPEAKER", "default")
            logger.info(f"Initialized Fish Speech TTS settings with API: {setting.fish_speech_api}")
            
        elif provider in ['cosyvoice_v2', 'cosyvoicev2', 'cosyvoice2']:
            setting.tts_service_provider = 'cosyvoice_v2'
            setting.cosyvoice_api_key = os.getenv("COSYVOICE_API_KEY")
            setting.cosyvoice_model = os.getenv("COSYVOICE_MODEL", "cosyvoice-v2")
            setting.cosyvoice_default_voice = os.getenv("COSYVOICE_DEFAULT_VOICE", "longxiaochun_v2")
            setting.cosyvoice_audio_format = os.getenv("COSYVOICE_AUDIO_FORMAT", "wav_24k")
            setting.cosyvoice_speed = float(os.getenv("COSYVOICE_SPEED", "1.0"))
            logger.info(f"Initialized CosyVoice V2 TTS settings with voice: {setting.cosyvoice_default_voice}")
            
        else:
            # Try to use cosyvoice_v2 as fallback if available
            try:
                logger.warning(f"Unsupported TTS provider: {tts_service_provider}. Attempting to use cosyvoice_v2 as fallback.")
                setting.tts_service_provider = 'cosyvoice_v2'
                setting.cosyvoice_api_key = os.getenv("COSYVOICE_API_KEY")
                setting.cosyvoice_model = os.getenv("COSYVOICE_MODEL", "cosyvoice-v2")
                setting.cosyvoice_default_voice = os.getenv("COSYVOICE_DEFAULT_VOICE", "longxiaochun_v2")
                setting.cosyvoice_audio_format = os.getenv("COSYVOICE_AUDIO_FORMAT", "wav_24k")
                setting.cosyvoice_speed = float(os.getenv("COSYVOICE_SPEED", "1.0"))
                logger.info(f"Successfully fell back to cosyvoice_v2 for provider: {tts_service_provider}")
                
            except Exception as fallback_error:
                error_msg = f"Unsupported TTS service provider: {tts_service_provider} and fallback to cosyvoice_v2 failed: {str(fallback_error)}"
                logger.error(error_msg)
                raise NotImplementedError(error_msg) from fallback_error
                
    except Exception as e:
        error_msg = f"Error initializing TTS settings for provider {provider}: {str(e)}"
        logger.error(error_msg, exc_info=True)
        raise ValueError(error_msg) from e


if __name__ == '__main__':
    setting = get_default_setting(os_name='Windows', language='zh', tts_service_provider='azure')
    print(setting.tts_api_key)
